import 'package:card_swiper/card_swiper.dart';
import 'package:chathouse/model/hot_service.dart';
import 'package:chathouse/pages/client/home/service_detail.dart';
import 'package:chathouse/public/Config.dart';
import 'package:chathouse/web_socket/web_socket_channel.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';

import '../../../constant/app_constant.dart';
import '../../../model/advertise.dart' as adver;
import '../../../model/advertise.dart';
import '../../../model/member_info.dart';
import '../../../model/web_model.dart';
import '../../../push/chat_house_push.dart';
import '../../../util/base_utils.dart';
import '../../../util/log.dart';
import '../../../widgets/base_webview.dart';
import '../../../widgets/custom_contro.dart';
import '../../route_manager/root_route_manager.dart';
import 'ServiceAndRepairPage.dart';
import 'legal_engineering_page.dart';

/// @class : ClientHomePage
/// @date : 2023-02-22 17:45
/// @name : LFC
/// @description :客户端首页
///
class ClientHomePage extends StatefulWidget {
  const ClientHomePage({Key? key}) : super(key: key);

  @override
  State<ClientHomePage> createState() => _ClientHomePageState();
}

class _ClientHomePageState extends State<ClientHomePage>
    with AutomaticKeepAliveClientMixin, NavigationHelper {
  HotService? hotService;

  @override
  bool get wantKeepAlive => true;

  SwiperController? swiperController;
  SwiperController? swiperController2;

  @override
  void dispose() {
    swiperController?.dispose();
    swiperController2?.dispose();
    super.dispose();
  }

  List<adver.Rows>? firstBanner;
  List<adver.Rows>? secondBanner;

  @override
  void initState() {
    super.initState();
    // if (Platform.isAndroid) {
    //   // 设置android状态栏为透明的沉浸，在渲染之前MaterialApp组件会覆盖掉这个值。
    //   SystemUiOverlayStyle systemUiOverlayStyle = const SystemUiOverlayStyle(
    //     statusBarColor: Colors.transparent, //状态栏的颜色根据需要更改
    //   );
    //   SystemChrome.setSystemUIOverlayStyle(systemUiOverlayStyle);
    // }
    Obj.showLoading();

    //banner1
    Apis.getAdvertise({"pattern": "1", "position": "1"}).then((response) {
      setState(() {
        var data = response?.data;
        Advertise? ad = Advertise.fromJson(data);
        firstBanner = ad.rows;
        // var oldLength = ad.rows?.length ?? 0;
        // if (oldLength > 1) {
        //   var halfLength = (oldLength / 2).ceil();
        //   firstBanner = ad.rows!.sublist(0, halfLength);
        //   secondBanner = ad.rows!.sublist(halfLength);
        //   LogUtil.d("oldLength ${oldLength}");
        //   LogUtil.d("firstBanner ${firstBanner?.length ?? 0}");
        //   LogUtil.d("secondBanner ${secondBanner?.length ?? 0}");
        // } else {
        //   firstBanner = ad.rows;
        //   secondBanner = ad.rows;
        //   LogUtil.d("firstBanner1 ${firstBanner?.length ?? 0}");
        //   LogUtil.d("secondBanner2 ${secondBanner?.length ?? 0}");
        // }
      });
    });

    //banner2
    Apis.getAdvertise({"pattern": "1", "position": "2"}).then((response) {
      setState(() {
        var data = response?.data;
        Advertise? ad = Advertise.fromJson(data);
        secondBanner = ad.rows;
        // var oldLength = ad.rows?.length ?? 0;
        // if (oldLength > 1) {
        //   var halfLength = (oldLength / 2).ceil();
        //   firstBanner = ad.rows!.sublist(0, halfLength);
        //   secondBanner = ad.rows!.sublist(halfLength);
        //   LogUtil.d("oldLength ${oldLength}");
        //   LogUtil.d("firstBanner ${firstBanner?.length ?? 0}");
        //   LogUtil.d("secondBanner ${secondBanner?.length ?? 0}");
        // } else {
        //   firstBanner = ad.rows;
        //   secondBanner = ad.rows;
        //   LogUtil.d("firstBanner1 ${firstBanner?.length ?? 0}");
        //   LogUtil.d("secondBanner2 ${secondBanner?.length ?? 0}");
        // }
      });
    });

    //TODO 弹窗广告
    Apis.getAdvertise({"pattern": 2}).then((value) {
      // print("getAdvertise2 value:$value");
      //TODO
    });

    Apis.getHotServiceListSix().then((response) {
      Obj.dismissLoading();
      setState(() {
        var data = response?.data;
        hotService = HotService.fromJson(data);
        LogUtil.d("getHotServiceList success:${hotService}");
        // LogUtil.d("getHotServiceList success:${hotService!.rows!.length}");
      });
    }).catchError((error) {
      Obj.dismissLoading();
      LogUtil.d("--getHotServiceListSix 请求失败--：${error.toString()}");
    });
    getMembersInfo();
    swiperController = SwiperController();
    swiperController2 = SwiperController();


    // ChatHousePush.instance.jpush.setBadge(0);
    // ChatHousePush.instance.jpush.isNotificationEnabled().then((value) => null);
  }

  getMembersInfo() {
    Apis.getMembersInfo().then((value) {
      Obj.dismissLoading();
      var jsonData = value?.data;
      MemberInfo info = MemberInfo.fromJson(jsonData);
      SpUtil.putObject(AppConstant.memberInfo, info);
      // socket 连接
      MyWebSocketChannel.instance.initSocket();
      Obj.dismissLoading();
    }).catchError((error) {
      Obj.dismissLoading();
      LogUtil.d("getMembersInfo error");
    });
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);

    return Scaffold(
      backgroundColor: Colors.white,
      body: CustomScrollView(
        slivers: [
          SliverToBoxAdapter(
            child: Visibility(
              visible: firstBanner != null,
              child: SizedBox(
                height: 212.w,
                child: Swiper(
                  itemBuilder: (context, index) {
                    return ImageUtils.image(firstBanner![index].img ?? "",
                        imageType: ImageType.NETWORK, fit: BoxFit.fitWidth);
                  },
                  autoplay: true,
                  outer: true,
                  itemCount: firstBanner?.length ?? 0,
                  pagination: SwiperPagination(
                      margin: EdgeInsets.only(top: 6.w),
                      builder:
                          SwiperCustomPagination(builder: (context, config) {
                        return ConstrainedBox(
                          child: Center(
                            child: Container(
                              alignment: Alignment.center,
                              width: double.infinity,
                              color: Colors.white,
                              child: ListView.separated(
                                shrinkWrap: true,
                                scrollDirection: Axis.horizontal,
                                itemCount: config.itemCount,
                                itemBuilder: (BuildContext context, int index) {
                                  return Container(
                                    height: 5.w,
                                    width: 30.w,
                                    decoration: BoxDecoration(
                                        color: config.activeIndex == index
                                            ? MyColors.green_69157608
                                            : MyColors.gary_199199199,
                                        borderRadius:
                                            BorderRadius.circular(1.w)),
                                  );
                                },
                                separatorBuilder:
                                    (BuildContext context, int index) {
                                  return Container(
                                      width: 8.w, color: Colors.white);
                                },
                              ),
                            ),
                          ),
                          constraints: BoxConstraints.expand(
                              height: 4.w, width: double.infinity),
                        );
                      })),
                  controller: swiperController,
                  autoplayDisableOnInteraction: true,
                  control: CustomSwiperControl(
                      iconPrevious: ImageUtils.image(Res.arrow_previous,
                              width: 23.w, height: 23.w)
                          .setOnClickListener(() {
                        swiperController?.stopAutoplay();
                        swiperController?.previous(animation: true);
                      }),
                      iconNext: ImageUtils.image(Res.arrow_next,
                              width: 23.w, height: 23.w)
                          .setOnClickListener(() {
                        swiperController?.stopAutoplay();
                        swiperController?.next(animation: true);
                      })),
                  onTap: (int index) {
                    Get.to(BaseWebViewPage(
                      webModel: WebModel(firstBanner![index].title ?? "",
                          firstBanner![index].url ?? ""),
                    ));
                  },
                ),
              ),
            ),
          ),
          SliverToBoxAdapter(
            child: Container(
              margin: EdgeInsets.only(top: 12.w, right: 12.w, left: 12.w),
              height: 152.w,
              child: Row(
                children: [
                  Expanded(
                    child: ImageUtils.image(Res.service_test_building,
                            radius: 20.w)
                        .setOnClickListener(() {
                      // Get.to(
                      //     ServiceDetailPage(AppConstant.testBuildingService));
                      toServeDetailPage(AppConstant.testBuildingService);
                    }, isInkWell: true),
                  ),
                  SizedBox(width: 8.w),
                  Expanded(
                    child: ImageUtils.image(Res.service_water_seepage,
                            radius: 20.w)
                        .setOnClickListener(() {
                      // Get.to(ServiceDetailPage(AppConstant.testWaterService));
                      toServeDetailPage(AppConstant.testWaterService);
                    }, isInkWell: true),
                  ),
                  SizedBox(width: 8.w),
                  Expanded(
                      child: Column(
                    children: [
                      Expanded(
                        child: Container(
                                child: ImageUtils.image(
                                    Res.service_legal_engineering))
                            .setOnClickListener(() {
                          navigateTo(const LegalEngineeringPage());
                          // Get.to(const LegalEngineeringPage());
                        }, isInkWell: true),
                      ),
                      SizedBox(height: 2.w),
                      Expanded(
                        child: Container(
                          child: ImageUtils.image(
                            Res.service_repair,
                          ),
                        ).setOnClickListener(() {
                          // Get.to(const ServiceAndRepairPage());
                          navigateTo(const ServiceAndRepairPage());
                        }, isInkWell: true),
                      ),
                    ],
                  )),
                ],
              ),
            ),
          ),
          SliverToBoxAdapter(
            child: Visibility(
              visible: secondBanner != null,
              child: Container(
                margin: EdgeInsets.only(top: 18.w),
                height: 200.w,
                child: Swiper(
                  itemBuilder: (context, index) {
                    return ImageUtils.image(secondBanner![index].img ?? "",
                        imageType: ImageType.NETWORK, fit: BoxFit.fitWidth);
                  },
                  autoplay: true,
                  itemCount: secondBanner?.length ?? 0,
                  outer: true,
                  pagination: SwiperPagination(
                      margin: EdgeInsets.only(top: 6.w),
                      builder:
                          SwiperCustomPagination(builder: (context, config) {
                        return ConstrainedBox(
                          child: Center(
                            child: Container(
                              alignment: Alignment.center,
                              width: double.infinity,
                              color: Colors.white,
                              child: ListView.separated(
                                shrinkWrap: true,
                                scrollDirection: Axis.horizontal,
                                itemCount: config.itemCount,
                                itemBuilder: (BuildContext context, int index) {
                                  return Container(
                                    height: 5.w,
                                    width: 30.w,
                                    decoration: BoxDecoration(
                                        color: config.activeIndex == index
                                            ? MyColors.green_69157608
                                            : MyColors.gary_199199199,
                                        borderRadius:
                                            BorderRadius.circular(1.w)),
                                  );
                                },
                                separatorBuilder:
                                    (BuildContext context, int index) {
                                  return Container(
                                      width: 8.w, color: Colors.white);
                                },
                              ),
                            ),
                          ),
                          constraints: BoxConstraints.expand(
                              height: 4.w, width: double.infinity),
                        );
                      })),
                  controller: swiperController2,
                  autoplayDisableOnInteraction: true,
                  control: CustomSwiperControl(
                      iconPrevious: ImageUtils.image(Res.arrow_previous,
                              width: 23.w, height: 23.w)
                          .setOnClickListener(() {
                        swiperController2?.stopAutoplay();
                        swiperController2?.previous(animation: true);
                      }),
                      iconNext: ImageUtils.image(Res.arrow_next,
                              width: 23.w, height: 23.w)
                          .setOnClickListener(() {
                        swiperController2?.stopAutoplay();
                        swiperController2?.next(animation: true);
                      })),
                  onTap: (int index) {
                    Get.to(BaseWebViewPage(
                      webModel: WebModel(secondBanner![index].title ?? "",
                          secondBanner![index].url ?? ""),
                    ));
                  },
                  // control: SwiperControl(iconPrevious: IconData(),),
                ),
              ),
            ),
          ),
          SliverToBoxAdapter(
            child: Container(
              margin: EdgeInsets.only(top: 20.w, bottom: 15.w),
              child: Text(
                "熱門服務",
                textAlign: TextAlign.center,
                style: getTextStyle(25.sp,
                    fontType: FontType.BOLD, color: MyColors.green_6915761),
              ),
            ),
          ),
          SliverPadding(
            padding: EdgeInsets.symmetric(horizontal: 28.w),
            sliver: SliverGrid(
                delegate: SliverChildBuilderDelegate(
                  (BuildContext ctx, int index) {
                    return Column(
                      children: [
                        AspectRatio(
                          aspectRatio: 162 / 108,
                          child: ImageUtils.image(
                              hotService?.data![index].thumbnailImg ?? "",
                              imageType: ImageType.NETWORK,
                              fit: BoxFit.fill,
                              radius: 20.w),
                        ),
                        Text(hotService?.data![index].serviceName ?? "",
                            maxLines: 2,
                            textAlign: TextAlign.center,
                            style: getTextStyle(
                              16.sp,
                              fontType: FontType.BOLD,
                              color: MyColors.black_0000011,
                            )),
                      ],
                    ).setOnClickListener(() {
                      // Get.to(ServiceDetailPage(
                      //     hotService?.rows![index].serviceId ??
                      //         AppConstant.testWaterService));
                      toServeDetailPage(hotService?.data![index].serviceId ??
                          AppConstant.testWaterService);
                    }, isInkWell: true);
                  },
                  childCount: hotService?.data?.length ?? 0,
                ),
                gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                  crossAxisCount: 2,
                  childAspectRatio: 1,
                  mainAxisSpacing: 0.w,
                  crossAxisSpacing: 28.w,
                )),
          ),
        ],
      ),
    );
  }

  void toServeDetailPage(num id) {
    // Get.to(ServiceDetailPage(id));
    navigateTo(ServiceDetailPage(id));
  }
}
